<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;

use think\Pgettext\Mo;
use think\Pgettext\Po;
use think\Pgettext\Stringset;

class Msgset extends Admin {

	public function index() {
		if (IS_POST) {
			$mo=new Mo();
			$po=new Po();
			$language=$_POST['language'];
			$flag=$_POST['flag'];

			foreach($_FILES['file']['name'] as $key => $val){
				$filename=$val;
				$format=substr($val,strlen($val)-2,2);  //从文件名中获取文件格式
				if($format=='mo'){
					$stringset=$mo->fromFile($_FILES['file']['tmp_name'][$key]);
				}elseif($format=='po'){
					$stringset=$po->fromFile($_FILES['file']['tmp_name'][$key]);
				}else{
					//return $this->error("请上传mo或者po文件");
					continue;
				}
				$this->addFile($stringset,$language,$filename,$flag);  //加入数据库
			}
			return $this->success("添加成功！", url('admin/msgset/index'),"",2);
		} else {
			$this->setMeta("文件导入");
			return $this->fetch();
		}
	}
	public function addFile($stringset,$language,$filename,$flag=0){
		foreach($stringset->catalog() as $key => $val){
			if(!empty($val['id'])){
				$msgid=addslashes($val['id']);   //字符串转义     反转义函数stripslashes
				$where_msgid=addslashes($msgid);		//数据库查询时候要多加一次转义
				$isExists=db("msgid")->where("msgid='{$where_msgid}'")->find();
				//msgid表添加数据
				if(empty($isExists)){
					$dataMsgid['msgid']=$msgid;
					$msgid_id=db("msgid")->insertGetId($dataMsgid);
				}else
					$msgid_id=$isExists['id'];
				if(!empty($val['strings'][0])){  //没翻译的不加入数据库
					//msgstr表添加数据
					$isExistsStr=db("msgstr")->where("msgid_id={$msgid_id} and language='{$language}'")->select();
					if(empty($isExistsStr)){
						$dateMsgstr['msgid_id']=$msgid_id;   			//msgid_id
						$dateMsgstr['msgstr']=addslashes($val['strings'][0]);  //转义
						$dateMsgstr['language']=$language;
						$dateMsgstr['flag']=1;
						$dateMsgstr['file_name']=substr($filename,0,strlen($filename)-3);		//文件名称
						db("msgstr")->insert($dateMsgstr);
					}else{
						$is_same=0;	$is_same_id=0;	//判断是否为相同翻译
						foreach($isExistsStr as $k => $v){
							if($v['msgstr']==addslashes($val['strings'][0])){
								$is_same=1;			//存在相同翻译
								$is_same_id=$v['id'];
							}
						}
						if($is_same==0){
							if($flag){	//如果是标准翻译，把其他翻译设为非标准
								db("msgstr")->where("msgid_id={$msgid_id} and language='{$language}'")->update(array("flag"=>0));
							}
							$dateMsgstr['msgid_id']=$msgid_id;   			//msgid_id
							$dateMsgstr['msgstr']=addslashes($val['strings'][0]);  //转义
							$dateMsgstr['language']=$language;
							$dateMsgstr['flag']=$flag;
							$dateMsgstr['file_name']=substr($filename,0,strlen($filename)-3);		//文件名称
							db("msgstr")->insert($dateMsgstr);
						}else{
							if($flag){  //在设为标准翻译，且已存在相同的情况下，吧相同这个设为标准翻译，其他设置为0
								db("msgstr")->where("msgid_id={$msgid_id} and language='{$language}'")->update(array("flag"=>0));
								db("msgstr")->where("id={$is_same_id}")->update(array("flag"=>1));
							}
						}
					}
				}
			}
		}
	}

	//上传导入压缩文件
	public function uploadzipfile() {
		if (IS_POST) {
			$flag=$_POST['flag'];
			$format=substr($_FILES['file']['name'],strlen($_FILES['file']['name'])-3,3);  //从文件名中获取文件格式
			if($format=="zip"){
				$zip = new \ZipArchive;
				$res = $zip->open($_FILES['file']['tmp_name']);
				if ($res === TRUE) {
					//解压缩到uploads/mopo/时间戳  文件夹
					$url='uploads/mopo/'.time();
					$zip->extractTo($url);
					$zip->close();
				} else {
					$this->error("请上传未损坏的zip压缩文件");
				}
			}elseif($format=="rar"){
				if(!extension_loaded('rar'))//判断rar 扩展是否安装
				{
					$this->error("请先安装php_rar扩展");
				}
				$rar_file = rar_open($_FILES['file']['tmp_name']) or $this->error("请上传未损坏的rar压缩文件");
				$entries = rar_list($rar_file);
				$url='uploads/mopo/'.time();
				foreach ($entries as $entry) {
					$entry->extract($url);
				}
				rar_close($rar_file);
			}else{
				$this->error("请上传正确的rar或zip压缩文件");
			}
			$exec="php think mopo:upload ".$_SERVER['DOCUMENT_ROOT']."/".$url." ".$flag;
			$last_line = exec($exec);//执行批处理
			if($last_line=='ok'){
				return $this->success("添加成功！", url('admin/msgset/uploadzipfile'),"",2);
			}else{
				return $this->error("处理失败", url('admin/msgset/uploadzipfile'),"",2);
			}
		} else {
			$this->setMeta("导入压缩包");
			return $this->fetch();
		}
	}
	//修改
	public function editStr() {
		$flag=$_GET['flag'];
		$check_flag=$_GET['check_flag'];
		$where="a.id>0 ";
		if(!empty($_GET['language'])){
			$str = join(",",$_GET['language']);				 //数组转字符串
			$language = "'".str_replace(",","','",$str)."'";	//每个语言加入单引号，sql字符串搜索必须加单引号
			$where.=" and language in({$language})";
		}
		if(!empty($_GET['file_name'])){
			$file_name=$_GET['file_name'];
			$where.=" and file_name = '{$file_name}'";
		}
		if(!is_null($flag)&&$flag!=-1){
			$where.=" and flag = {$flag}";
		}
		if(!is_null($check_flag)&&$check_flag!=-1){
			$where.=" and check_flag = {$check_flag}";
		}
		$msgstrwhere=$where;	//msgstr单表查询时候用，因为不能去查询下面的msgid
		if(!empty($_GET['msgid'])){
			$msgid=$_GET['msgid'];
			$where.=" and msgid LIKE '%{$msgid}%'";
		}

		//每页显示数量
		if(empty(session('nums'))){
			session('nums',10);
			$nums=10;
		}else{
			$nums=session('nums');
		}
		//$list = db('msgstr')->alias('a')->field('msgid,msgstr,a.id,language,flag,check_flag,file_name')->where($where)->join('msgid b','a.msgid_id = b.id')->order('a.id desc')->paginate(15)->appends(array('language'=>$language,'file_name'=>$file_name,'msgid'=>$msgid));//联表查询符合条件的msgstr

		//联表查询符合条件的msgid，主要因为分页的影响，必须按照msgid进行分页
		$list = db('msgid')->alias('a')->field('a.id,msgid')->group('msgid')->where($where)->join('msgstr b','b.msgid_id = a.id')->order('a.id desc')->paginate($nums)->appends(array('language'=>$_GET['language'],'file_name'=>$file_name,'msgid'=>$msgid,'flag'=>$_GET['flag'],'check_flag'=>$_GET['check_flag']));

		//根据符合条件的msgid，查询对应的msgstr
		foreach($list as $key => $val){
			$msgwhere=$msgstrwhere." and msgid_id  = {$val['id']}";
			//print_r($wherestr);print_r("\n");
			$msgstrlist=db('msgstr')->alias('a')->where($msgwhere)->select();
			$newList[$val['msgid']]=$msgstrlist;
		}
		//查询所有文件的文件名，用于搜索
		$filelist=db('msgstr')->distinct('file_name')->field('file_name')->select();
		//获取分页每页显示条数
		$numslist=db('config')->field("value")->where("name='list_rows'")->find();
		$numslists=explode(',',$numslist['value']);
		$this->assign('filelist',$filelist);
		$this->assign('list',$newList);
		$this->assign('language',$_GET['language']);
		$this->assign('file_name',$file_name);
		$this->assign('msgid',$msgid);

		$this->assign('flag',$_GET['flag']);
		$this->assign('check_flag',$_GET['check_flag']);
		$this->assign('page',$list->render());
		$this->assign('nums',$nums);
		$this->assign('numslists',$numslists);
		$this->setMeta('编辑');
		return $this->fetch();
	}

	//修改msgstr
	public function updateMsgstr() {
		$id=$_POST['id'];
		if(empty($id)){
			echo json_encode(array("error"=>1,"msg"=>"缺失id"));
			exit;
		}
		if(!empty($_POST['msgstr'])){
			$update['msgstr']=$_POST['msgstr'];
		}
		if(!is_null($_POST['flag'])){
			$update['flag']=$_POST['flag'];
			if($_POST['flag']==1){		//指定一个为标准时候，先把同种语言下的翻译全部设置为0
				$strinfo=db('msgstr')->where("id={$id}")->find();
				if(!empty($strinfo))
					db('msgstr')->where("msgid_id={$strinfo['msgid_id']} and language='{$strinfo['language']}'")->update(array('flag'=>'0'));
			}
		}
		if(!is_null($_POST['check_flag'])){
			$update['check_flag']=$_POST['check_flag'];
		}
		if(!is_null($_POST['grade'])){
			$update['grade']=$_POST['grade'];
		}
		if(empty($update)){
			echo json_encode(array("error"=>1,"msg"=>"缺失更新数据"));
			exit;
		}
		$re=db('msgstr')->where("id={$id}")->update($update);
		if($re){
			echo json_encode(array("error"=>0,"msg"=>"修改成功"));
			exit;
		}else{
			echo json_encode(array("error"=>1,"msg"=>"修改失败"));
			exit;
		}
	}
	//新增一条msgstr
	public function addMsgstr() {
		$add['msgid_id']=$_POST['msgid_id'];
		$add['msgstr']=$_POST['msgstr'];
		$add['language']=$_POST['language'];
		$add['flag']=$_POST['flag'];
		$add['file_name']=$_POST['file_name'];
		$add['check_flag']=$_POST['check_flag'];
		$add['grade']=$_POST['grade'];
		//print_r($add);exit;
		if($add['flag']==1){		//指定一个为标准时候，先把同种语言下的翻译全部设置为0
			$count=db('msgstr')->where("msgid_id={$add['msgid_id']} and language='{$add['language']}' and flag=1")->count();
			if($count){
				$re=db('msgstr')->where("msgid_id={$add['msgid_id']} and language='{$add['language']}'")->update(array('flag'=>'0'));
				if(!$re){
					echo json_encode(array("error"=>1,"msg"=>"修改失败"));
					exit;
				}
			}

		}
		$re=db('msgstr')->insert($add);
		if($re){
			echo json_encode(array("error"=>0,"msg"=>"添加成功"));
			exit;
		}else{
			echo json_encode(array("error"=>1,"msg"=>"添加失败"));
			exit;
		}
	}
	//删除msgstr
	public function delMsgstr() {
		$id=$_POST['id'];
		if(empty($id)){
			echo json_encode(array("error"=>1,"msg"=>"错误请求"));
			exit;
		}
		$re=db('msgstr')->where("id={$id}")->delete();
		if($re){
			echo json_encode(array("error"=>0,"msg"=>"删除成功"));
			exit;
		}else{
			echo json_encode(array("error"=>1,"msg"=>"删除失败"));
			exit;
		}
	}
	//导出mopo文件
	public function export() {
		if (IS_POST) {
			$data   = $this->request->post();
			$stringset = new Stringset();
			if(empty($data['file_name']))
				return $this->error("请选择导出文件");
			$where="file_name='{$data['file_name']}' and language='{$data['language']}' and flag=1";
			$list = db('msgstr')->alias('a')->field('msgid,msgstr')->where($where)->join('msgid b','a.msgid_id = b.id')->select();
			if(empty($list)){
				return $this->error("没有该文件的语言翻译");
			}

			//增加文件头
			$head["msgid"]="";
			$head["msgstr"]="Language: {$data['language']}\nContent-Type: text/plain; charset=UTF-8";
			$stringset->add($head);
			$filename=substr($data['file_name'],0,strlen($data['file_name'])-2);
			foreach($list as $key => $val){
				$val['msgid']=stripslashes($val['msgid']);//从数据库导出后反转义
				$val['msgstr']=stripslashes($val['msgstr']);
				$stringset->add($val);
			}

			if($data['file_type']=='po'){
				$po=new Po();
				$po->toFile($stringset,$filename.'po');//导出po文件
			}elseif($data['file_type']=='mo'){
				$mo=new Mo();
				$mo->toFile($stringset,$filename.'mo');//导出mo文件
			}
		}else{
			$filelist=db('msgstr')->distinct('file_name')->field('file_name')->select();
			$this->assign('filelist',$filelist);
			$this->setMeta('导出文件');
			return $this->fetch();
		}
	}

	//读取mo文件-》
	public function batchTranslation() {
		if (IS_POST) {
			$mo=new Mo();
			$po=new Po();
			$format=substr($_FILES['file']['name'],strlen($_FILES['file']['name'])-2,2);
			if($format=='mo'){
				$stringset=$mo->fromFile($_FILES['file']['tmp_name']);
			}elseif($format=='po'){
				$stringset=$po->fromFile($_FILES['file']['tmp_name']);
			}else{
				echo json_encode(array("error"=>1,"msg"=>"请上传正确文件"));
				exit;
			}
			$language=$_POST['language'];
			//print_r($stringset->catalog());exit;
			$canTranslate=0;$list=0;
			foreach($stringset->catalog() as $key => $val){
				if(!empty($val['id'])){
					$list++;
					$msgid=addslashes(addslashes($val['id']));
					$where="msgid=".'"'.$msgid.'" and language="'.$language.'" and flag=1 ';
					//print_r($where);exit;
					$info = db('msgstr')->alias('a')->field('msgid,msgstr')->where($where)->join('msgid b','a.msgid_id = b.id')->find();
					$aa[]=$info;
					if(!empty($info['msgstr'])){
						$canTranslate++;
					}
				}
			}
			//print_r($stringset->catalog());exit;
			$result=$list." 条记录,可翻译 ".$canTranslate." 条";
			echo json_encode(array("error"=>0,"msg"=>$result,"canTranslate"=>$canTranslate));
			exit;
		}else{
			$this->setMeta("翻译文件");
			return $this->fetch();
		}
	}

	//系统翻译—》导出mo文件
	public function translation() {
		if (IS_POST) {
			//print_r($_POST);exit;
			$mo=new Mo();
			$po=new Po();

			$stringset_new = new Stringset();

			$format=substr($_FILES['file']['name'],strlen($_FILES['file']['name'])-2,2);
			$filename=substr($_FILES['file']['name'],0,strlen($_FILES['file']['name'])-2);
			if($format=='mo'){
				$stringset=$mo->fromFile($_FILES['file']['tmp_name']);
			}elseif($format=='po'){
				$stringset=$po->fromFile($_FILES['file']['tmp_name']);
			}else{
				echo json_encode(array("error"=>1,"msg"=>"请上传正确文件"));
				exit;
			}
			$language=$_POST['language'];
			//print_r($stringset->catalog());exit;

			//增加文件头
			$head["msgid"]="";
			$head["msgstr"]="Language: {$language}\nContent-Type: text/plain; charset=UTF-8";
			$stringset_new->add($head);


			foreach($stringset->catalog() as $key => $val){
				if(!empty($val['id'])){
					$val_new['msgid']=$val['id'];
					$msgid=addslashes(addslashes($val['id']));
					$info = db('msgstr')->alias('a')->field('msgid,msgstr')->where("msgid='{$msgid}' and language='{$language}' and flag=1")->join('msgid b','a.msgid_id = b.id')->find();
					if(!empty($info)){
						//$stringset->set($val['id'],$info['msgstr']);
						$val_new['msgstr']=stripslashes($info['msgstr']);
					}else{
						$val_new['msgstr']="";
					}
					$stringset_new->add($val_new);
				}
			}
			if($_POST['file_type']=='mo')
				$mo->toFile($stringset_new,$filename.'mo');//导出mo文件
			elseif($_POST['file_type']=='po')
				$po->toFile($stringset_new,$filename.'po');//导出mo文件
			//print_r($stringset->catalog());exit;
		}
	}

	//系统翻译—》导出mo文件
	public function formatConversion() {
		if (IS_POST) {
			$mo=new Mo();
			$po=new Po();
			$format=substr($_FILES['file']['name'],strlen($_FILES['file']['name'])-2,2);
			$filename=substr($_FILES['file']['name'],0,strlen($_FILES['file']['name'])-2);
			if($format=='mo'){
				$stringset=$mo->fromFile($_FILES['file']['tmp_name']);
			}elseif($format=='po'){
				$stringset=$po->fromFile($_FILES['file']['tmp_name']);
			}else{
				return $this->error("请上传mo或者po文件");
			}
			//print_r($stringset->catalog());exit;
			if($_POST['file_type']=='mo')
				$mo->toFile($stringset,$filename.'mo');//导出mo文件
			elseif($_POST['file_type']=='po')
				$po->toFile($stringset,$filename.'po');//导出mo文件
		}else{
			$this->setMeta('格式转换');
			return $this->fetch();
		}
	}
	//批处理
	public function processingBatch() {
		if (IS_POST) {
			$exec="php think mopo:";
			if($_POST["batchtype"]==1){
				$exec.="upload";
			}elseif($_POST["batchtype"]==2){
				$exec.="translate";
			}
			if(empty($_POST["url"])){
				echo json_encode(array("error"=>1,"msg"=>"请输入文件路径"));
			}else{
				$exec.=" ".$_POST["url"];
			}
			if($_POST["batchtype"]==1&&$_POST["flag"]==1){
				$exec.=" 1";
			}
			if($_POST["batchtype"]==2&&$_POST["language"]==1){
				$exec.=" 1";
			}
			$last_line = exec($exec);//执行批处理
			//$last_line = system($exec);
			if($last_line=='ok'){
				echo json_encode(array("error"=>0,"msg"=>"处理完成"));
			}else{
				echo json_encode(array("error"=>1,"msg"=>$last_line));
			}
		}else{
			if(php_uname('s')=='Windows NT'){
				$root='f:';
				$file_list=scandir($root);
				foreach($file_list as $key => $val){
					//print_r($val);
					if(is_dir($root.'/'.$val)){
						$dir["text"]=$val;
						$dir['href']=$val;
						$dir['tags']=$root.'/'.$val;
						$dir['nodes']='';
						$dir_list[]=$dir;
					}
				}
			}elseif(php_uname('s')=='Linux'){
				print_r(scandir('/'));
			}
			//exit;
			$this->assign('dir_list',json_encode($dir_list));
			$this->setMeta("批处理");
			return $this->fetch();
		}
	}
	public function geturllist(){
		if(php_uname('s')=='Windows NT'){
			if(empty($_POST['id'])){
				for($i='c';$i<='h';$i++){
					$dir["name"]=$i.':';
					$dir['id']=$i.':';
					$dir['pid']='';
					$dir['isParent']=true;
					$dir_list[]=$dir;
				}
				echo json_encode($dir_list);exit;
				//$root='f:';
			}else{
				$root=$_POST['id'];
			}
		}elseif(php_uname('s')=='Linux'){
			if(empty($_POST['id'])){
				$root='/';
			}else{
				$root=$_POST['id'];
			}
		}
		$file_list=scandir($root);
		foreach($file_list as $key => $val){
			//print_r($val);
			if(is_dir($root.'/'.$val)){
				if($val!='.'&&$val!='..'&&!preg_match("/[\x7f-\xff]/", $val)){
					$dir["name"]=$val;
					$dir['id']=$root.'/'.$val;
					$dir['pid']=$root;
					$dir['isParent']=true;
					$dir_list[]=$dir;
				}
			}
		}
		echo json_encode($dir_list);exit;
	}
	//修改分页，每页显示条数
	public function editNums(){
		$nums=$_POST['nums'];
		session('nums', $nums);
		echo json_encode(array("error"=>0,"msg"=>"修改成功"));
	}
}